import showMenuIcon from '@/utils/showMenuIcon';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ModalForm, ProFormText, ProList, ProTable } from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Col, Form, message, Popconfirm, Row, Space } from 'antd';
import { useEffect, useRef, useState } from 'react';
import styles from './index.less';

import {
  get_api as get_menu_api,
  get_select_api,
  post_save_api as post_menu_save_api,
} from './api/MenuLimit';
import { delete_api, get_list_all_api, post_save_api } from './api/Role';
export default function Page() {
  const ref = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  // const [treeData, setTreeData] = useState([]);
  const [listAll, setListAll] = useState<GroupApi.RoleList[]>([]);
  const [active, setActive] = useState<string>('');
  const GetListAllRepository = async () => {
    const res = await get_list_all_api();
    // console.log(res.data.list);
    if (res.data) {
      const list = res.data.map((item: any) => {
        return {
          label: item.groupName,
          value: item.id,
        };
      });
      setListAll(list);
      if (list.length > 0) {
        setActive(list[0].value);
      }
    }
  };
  useEffect(() => {
    GetListAllRepository();
  }, []);

  const GetListSelectAllRepository = async () => {
    if (active !== '') {
      const res = await get_select_api(active);
      // console.log(res.data);
      if (res.data !== null) {
        const ids = res.data.map((item: any) => {
          return item.repDeptId;
        });
        setTimeout(() => {
          setSelectedRowKeys(ids);
        }, 200);
      } else {
        setSelectedRowKeys([]);
      }
    } else {
      setSelectedRowKeys([]);
    }
  };
  useEffect(() => {
    GetListSelectAllRepository();
  }, [active]);

  const [formAdd] = Form.useForm<GroupApi.Dto>();
  const [formEdit] = Form.useForm<GroupApi.Dto>();
  const columns: ProColumns<MenuApi.List>[] = [
    // {
    //   dataIndex: 'index',
    //   valueType: 'indexBorder',
    //   width: 100,
    // },
    {
      title: '部门名称',
      width: 240,
      search: false,
      dataIndex: 'deptName',
    },
  ];

  return (
    <PageContainer>
      <div className={styles.page}>
        <div className={styles.left}>
          <ProList<GroupApi.RoleList>
            headerTitle="组别"
            rowClassName={(row: GroupApi.RoleList) => {
              return active === row.value ? styles.active : '';
            }}
            toolBarRender={() => {
              return [
                <ModalForm<GroupApi.Dto>
                  key="add"
                  title="新增"
                  width={400}
                  trigger={<Button type="primary">新增</Button>}
                  form={formAdd}
                  autoFocusFirstInput
                  modalProps={{
                    destroyOnClose: true,
                    onCancel: () => console.log('run'),
                  }}
                  submitTimeout={2000}
                  onFinish={async (values) => {
                    // console.log(values);
                    const res = await post_save_api(values);

                    if (res.success) {
                      message.success('提交成功');
                      GetListAllRepository();
                    } else {
                      message.error('提交失败');
                    }

                    return res.success;
                  }}
                >
                  <Row>
                    <Col span={24}>
                      <ProFormText
                        rules={[{ required: true, message: '请输入组别名称' }]}
                        placeholder="请输入组别名称"
                        name="groupName"
                        label="组别名称"
                      />
                    </Col>
                    {/* <Col span={24}>
                      <ProFormTextArea placeholder="请输入备注" name="remark" label="备注" />
                    </Col> */}
                  </Row>
                </ModalForm>,
              ];
            }}
            onRow={(record: any) => {
              return {
                onClick: () => {
                  // console.log(record);
                  setActive(record.value);
                },
              };
            }}
            rowKey="value"
            dataSource={listAll}
            metas={{
              title: {
                dataIndex: 'label',
              },
              actions: {
                render: (text, row) => [
                  <ModalForm<GroupApi.Dto>
                    key="edit"
                    title="编辑"
                    width={400}
                    trigger={
                      <a
                        onClick={() => {
                          setTimeout(() => {
                            // 延迟填入数据，为了防止from未创建
                            const editRow: GroupApi.Dto = {
                              groupName: row.label,
                              id: row.value,
                            };
                            // console.log(editRow)
                            formEdit.setFieldsValue(editRow);
                          }, 100);
                        }}
                      >
                        编辑
                      </a>
                    }
                    form={formEdit}
                    autoFocusFirstInput
                    modalProps={{
                      forceRender: true,
                      destroyOnClose: true,
                      onCancel: () => console.log('run'),
                    }}
                    submitTimeout={2000}
                    onFinish={async (values) => {
                      console.log(values);
                      values.id = row.value;
                      const res = await post_save_api(values);

                      if (res.success) {
                        message.success('提交成功');
                        GetListAllRepository();
                      } else {
                        message.error('提交失败');
                      }

                      return res.success;
                    }}
                  >
                    <Row>
                      <Col span={24}>
                        <ProFormText
                          rules={[{ required: true, message: '请输入组别名称' }]}
                          placeholder="请输入组别名称"
                          name="groupName"
                          label="组别名称"
                        />
                      </Col>
                      {/* <Col span={24}>
                      <ProFormTextArea placeholder="请输入备注" name="remark" label="备注" />
                    </Col> */}
                    </Row>
                  </ModalForm>,

                  <Popconfirm
                    key="delete"
                    title="删除"
                    description="确认删除此条数据?"
                    onConfirm={async () => {
                      console.log(row.value);
                      const res = await delete_api(row.value);
                      if (res.success) {
                        message.success('删除成功');
                        GetListAllRepository();
                      } else {
                        message.error('删除失败');
                      }
                    }}
                    onCancel={() => {
                      message.error('删除已取消');
                    }}
                    okText="是"
                    cancelText="否"
                  >
                    <a style={{ color: '#F56C6C' }}>删除</a>
                  </Popconfirm>,
                ],
              },
            }}
          />
        </div>
        <div className={styles.right}>
          <ProTable<MenuApi.List>
            search={false}
            actionRef={ref}
            params={{ active }}
            request={async (params = {}) => {
              console.log(params);
              if (params.active) {
                const res = await get_menu_api(params.active);
                return {
                  data: res.data,
                  success: true,
                };
              }
              return {
                data: [],
                success: true,
              };
            }}
            rowKey="id"
            pagination={false}
            expandable={{
              childrenColumnName: 'routes',
              indentSize: 20,
            }}
            rowSelection={{
              checkStrictly: true,
              selectedRowKeys,
              onChange: (newSelectedRowKeys: React.Key[]) => {
                // console.log(selectedRows)
                setSelectedRowKeys(newSelectedRowKeys);
              },
            }}
            tableAlertOptionRender={({ selectedRowKeys }) => {
              return (
                <Space size={16}>
                  <a
                    onClick={async () => {
                      console.log(selectedRowKeys);
                      const req = selectedRowKeys.map((item) => {
                        return {
                          repDeptId: item,
                          deptGroupId: active,
                        };
                      });

                      const res = await post_menu_save_api(req);
                      console.log(res);
                      if (res.success) {
                        message.success('修改成功');
                      }
                    }}
                  >
                    确认修改
                  </a>
                </Space>
              );
            }}
            columns={columns}
            dateFormatter="string"
            toolBarRender={() => []}
          />
        </div>
      </div>
    </PageContainer>
  );
}
